package org.rainbow.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyRealm3 implements Realm {

	private static final Logger logger = LoggerFactory.getLogger(MyRealm3.class);
	
	////返回一个唯一的 Realm 名字
	public String getName() {
		return "myRealm3";
	}

	////判断此 Realm 是否支持此 Token
	public boolean supports(AuthenticationToken token) {
		//仅支持 UsernamePasswordToken 类型的 Token
		return token instanceof UsernamePasswordToken;
	}

	//根据 Token 获取认证信息
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		String username = (String)token.getPrincipal(); //得到用户名
		String password = new String((char[])token.getCredentials()); //得到密码
		if(!"rainbow".equals(username)) {
			throw new UnknownAccountException(); //如果用户名错误
		}
		if(!"123456".equals(password)) {
			throw new IncorrectCredentialsException(); //如果密码错误
		}
		logger.debug("myrealm3=============> 验证成功");
		//如果身份认证验证成功，返回一个 AuthenticationInfo 实现；
		return new SimpleAuthenticationInfo(username + "@qw.com", password, getName());
	}

}
